<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { systemApi } from '@/api'
import { ElMessage } from 'element-plus'
const router = useRouter()
const route = useRoute()
const refForm = ref()
const refTree = ref()
const loading = ref(false)
const id = computed(() => route.query.id || '')
const ruleForm = ref({
  roleName: '',
  description: '',
  menuId: []
})
const rules = ref({
  roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }]
})
const treeData = ref([])
const defaultProps = ref({
  children: 'children',
  label: 'permissionName'
})

onMounted(async () => {
  await getRoleMenus()
  if (id.value) {
    await getRoleDetail()
    await getRoleMenus(id.value)
  }
})

// 编辑角色
async function editRoleDetail() {
  loading.value = true
  ruleForm.value.menuId = getCheckedKeys()
  console.log(ruleForm.value.menuId, 'ruleForm.menuId')
  const params = {
    ...ruleForm.value
  }
  try {
    await systemApi.default.updateRoleBindingMenu(params)
    loading.value = false

    ElMessage.success('保存成功')
    goBack()
  } catch (error) {
    loading.value = false
  }
}
// 新增角色
async function addRole() {
  loading.value = true
  ruleForm.value.menuId = getCheckedKeys()
  const params = {
    ...ruleForm.value
  }
  try {
    await systemApi.default.addRoleAndBindingMenu(params)
    loading.value = false
    this.$message.success('创建成功')
    goBack()
  } catch (error) {
    loading.value = false
  }
}
// 获取角色详情
async function getRoleDetail() {
  const { data } = await systemApi.default.querySysRolesById({
    id: id.value
  })
  ruleForm.value = data
}
// 获取角色菜单
async function getRoleMenus(id) {
  const params = {
    rolesId: id || 1, // 1查admin所有菜单 , 有id的话是回显的接口
    expoId: null
  }
  const {
    data: { project }
  } = await systemApi.default.findPermissionsByRoles(params)
  // 如果有id, 就是回显的时候查询回显角色拥有的菜单
  if (id) {
    ruleForm.value.menuId = getMenus(project)
    let data = project
    let node = []
    data.forEach(item => {
      if (item.children && item.children.length > 0) {
        delete item['id']
        item.children.forEach(el => {
          node.push(el.id)
        })
      }
      node.push(item.id)
    })
    console.log(node, 'node')
    refTree.value?.setCheckedKeys(node)
  } else {
    project.forEach(item => {
      if (item.children && item.children.length > 0) {
        // 不显示导入证件列表该菜单
        item.children = item.children.filter(el => el.id != 440)
      }
    })
    treeData.value = project
  }
}
// 过滤后台返回来的数据, 获取id数组
function getMenus(data) {
  const arr = []
  data.forEach(item => {
    if (item.children && item.children.length) {
      arr.push(...getMenus(item.children))
    }
    arr.push(item.id)
  })
  return arr
}
// 获取所有选中的id
function getCheckedKeys() {
  return refTree.value
    ?.getCheckedKeys()
    .concat(refTree.value?.getHalfCheckedKeys())
}
async function submitForm(formName) {
  await refForm.value?.validate()
  id.value ? editRoleDetail() : addRole()
}
function goBack() {
  router.back()
}
</script>

<template>
  <div>
    <el-card shadow="never">
      <el-page-header
        :content="id ? '编辑角色权限' : '新增角色'"
        @back="goBack"
      ></el-page-header>
    </el-card>
    <el-card shadow="never">
      <el-form
        ref="refForm"
        :model="ruleForm"
        :rules="rules"
        label-width="100px"
        label-suffix="："
        label-position="left"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="ruleForm.roleName" clearable></el-input>
            </el-form-item>
            <el-form-item label="角色描述" prop="description">
              <el-input
                v-model="ruleForm.description"
                type="textarea"
                :autosize="{ minRows: 2, maxRows: 5 }"
              ></el-input>
            </el-form-item>
            <el-form-item label="菜单权限" prop="menuId">
              <el-tree
                ref="refTree"
                :data="treeData"
                show-checkbox
                node-key="id"
                highlight-current
                :props="defaultProps"
              ></el-tree>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" :loading="loading" @click="submitForm">
                立即提交
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
  </div>
</template>
